from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
import os
from datetime import datetime

app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{os.path.join(basedir, "licenses.db")}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
    'connect_args': {
        'timeout': 30,
        'check_same_thread': False
    }
}
db = SQLAlchemy(app)

class License(db.Model):
    __tablename__ = 'licenses'
    serial = db.Column(db.String(10), primary_key=True)
    max_users = db.Column(db.Integer, nullable=False)
    active_users = db.Column(db.Integer, nullable=False, default=0)

class ActiveUser(db.Model):
    __tablename__ = 'active_users'
    serial = db.Column(db.String(10), db.ForeignKey('licenses.serial'), primary_key=True)
    userid = db.Column(db.String(6), primary_key=True)
    last_check = db.Column(db.Integer, nullable=False)

    @property
    def last_check_dt(self):
        return datetime.fromtimestamp(self.last_check)

def initialize_database():
    """安全初始化数据库"""
    with app.app_context():
        try:
            db.create_all()
            print("数据库表已创建/验证")
        except Exception as e:
            print(f"数据库初始化错误: {str(e)}")

# 应用启动时初始化
initialize_database()

# 主页
@app.route('/')
def index():
    licenses = License.query.all()
    return render_template('index.html', licenses=licenses)

# 许可证详情页面
@app.route('/licenses/<string:serial>')
def license_detail(serial):
    license = License.query.get_or_404(serial)
    users = ActiveUser.query.filter_by(serial=serial).all()
    
    return render_template('license_detail.html', 
                         license=license, 
                         users=users)

if __name__ == '__main__':
    app.run(debug=True)